<template>
  <div
    v-if="Number(num) === -1 && boardChoice.tabs.length < 1"
    class="iminputdiv"
    @click.stop="addcursor($event,-1,-1,-1,-1)"
  >
    <div
      v-for="(Value, key) in inputarray"
      :key="key"
      class="row formula"
      :class="{'red':isCorrect?isCorrect[key]=='0':0,'green':isCorrect?isCorrect[key]=='1':0}"
      @click.stop="addcursor($event,key,-1,-1,-1)"
    >
      <template v-for="(value1, key1) in Value">
        <span
          v-if="value1.name=='cursor'"
          :key="key1"
          class="k-board cursor"
        />
        <formula-view
          v-else-if="value1.name=='fraction'||value1.name=='sqrt2'||value1.name=='sqrt3'||value1.name=='aimsup'||value1.name=='aimsub' || value1.name=='loop'"
          :key="key1"
          :data="value1"
          @emit-click="formulaClick($event, key, key1)"
        />
        <span
          v-else
          :key="key1"
          :class="[value1.name, value1.class, {'equal':value1.value === '='}]"
          @click.stop="addcursor($event,key,key1,-1,-1)"
        >{{ value1.value }}
        </span>
      </template>
    </div>
  </div>
  <!--选择填空-->
  <div
    v-else-if="boardChoice.tabs.length > 0"
    :class="{'im-select': cp_select}"
    class="im-wrap im-trans"
    @click.stop="addcursor($event,-1,-1,-1,-1)"
  >
    <div
      v-for="(itm, idx) in boardChoice.tabs.filter(item => item.select)"
      :key="idx"
      class="im-content"
    >
      <span
        v-if="itm.img"
        :key="'i' + idx"
        class="im-ipt-img"
      ><img
        :src="itm.img"
        class="im-choice-img"
      ></span>
      <span
        v-else
        :key="'t' + idx"
      >{{ itm.text }}</span>
    </div>
  </div>

  <div
    v-else-if="num < inputarray.length"
    :key="num"
    class="iminputdiv qti_fill_input"
    :class="{'red':isCorrect?isCorrect[num]==='0':0,'green':isCorrect?isCorrect[num]==='1':0}"
    @click.stop="addcursor($event,num,-1,-1,-1)"
  >
    <template v-if="inputarray[num].length === 0 && testdata.msubmitflag === 1">
      ?
    </template>

    <template
      v-for="(value1,key1) in inputarray[num]"
      v-else
    >
      <template
        v-if="inputarray[num].length==1&&value1.name=='aime'&&value1.value===''&&testdata.msubmitflag==1"
      >
        ?
      </template>
      <span
        v-else-if="value1.name=='cursor'"
        :key="key1"
        class="k-board cursor"
      />
      <span
        v-else-if="value1.name=='fraction'||value1.name=='sqrt2'||value1.name=='sqrt3'||value1.name=='aimsup'||value1.name=='aimsub'"
        :key="key1"
        :class="[value1.name, value1.class,{'click':is_cursor(value1.value)==1}]"
        @click.stop="addcursor($event,num,key1,-1,-1)"
      >
        <span
          class="enterdiv up"
          @click.stop="addcursor($event,num,key1,-1,'up')"
        >
          <span
            v-for="(value2,key2) in value1.value.up"
            :key="key2"
            dir="up"
            :class="value2.name"
            @click.stop="addcursor($event,num,key1,key2,'up')"
          >{{ value2.value }}
          </span>
        </span>
        <span
          class="enterdiv down"
          @click.stop="addcursor($event,num,key1,-1,'down')"
        >
          <span
            v-for="(value2,key2) in value1.value.down"
            :key="key2"
            dir="down"
            :class="value2.name"
            @click.stop="addcursor($event,num,key1,key2,'down')"
          >{{ value2.value }}
          </span>
        </span>
      </span>
      <span
        v-else
        :key="key1"
        :class="[value1.name, value1.class]"
        @click.stop="addcursor($event,num,key1,-1,-1)"
      >
        {{ value1.value }}
      </span>
    </template>
  </div>
</template>

<script>
import Bus from './view/emitBus.js';
import { _computeType, _defSymbols } from './view/utils.js';
import FormulaView from './view/FormulaView';

export default {
    name: 'InputBox',
    components: { FormulaView },
    props: {
        testdata: {
            type: Object,
            default () {
                return {
                    manswer: [],
                    msubmitflag: 0,
                };
            },
        },
        isCorrect: { // 输入框文字颜色
            type: Array,
            default () {
                return [];
            },
        },
        rootdata: { //
            type: Object,
            default () {
                return { imshow: 0 };
            },
        },
        num: { //
            type: [Number, String],
            default: -1,
        },
        group: { //
            type: [Number, String],
            default: -1,
        },
        inputarray: { //
            type: Array,
            default () {
                return [[]];
            },
        },
        id: { // 当前组件的id，用于下一空跳转标识
            type: [Number, String],
            default: '',
        },
        nextId: { // 下一空跳转的id
            type: [Number, String],
            default: '',
        },
        boardType: { // 键盘类型
            type: [Number, String],
            default: 'none',
        }, // 指定键盘类型
        value: {
            type: [String, Number],
            default: '',
        },
        /* 正确答案 */
        rightAnswers: {
            type: Array,
            default () {
                return [];
            },
        },
        subject: {
            type: [String, Number],
            default: 2, // 默认学科：数学
        }, // 学科编号
        writable: {
            type: Boolean,
            default: true, // 默认学科：数学
        }, // 是否可写
        boardChoice: {
            type: Object,
            default () {
                return {
                    tabs: [],
                    mode: 'single',
                };
            },
        }, // 选择填空
    },
    data () {
        return {
            maxlength: '',
            fullFirst: true,
            // inputarray: [[]],
            matchBoardType: 'combo', // 匹配的默认键盘
            matchBoardModel: 'chinese', // 匹配model
            prevBoardType: [], // 前一种键盘类型
            symbols: [_defSymbols(this.boardType)],
        };
    },
    computed: {
        cp_select () {
            return this.inputarray.some(itm => {
                return itm.find(el => el.name === 'cursor');
            });
        },
    },
    created: function () {
        Bus.iptComps.push({
            id: this.id,
            component: this,
            group: this.group,
            num: this.num,
        });
    },
    mounted () {
        let { boardType, rightAnswers } = this;
        /* 未传递键盘类型时，通过正确答案判断类型 */
        if (rightAnswers.length > 0 && rightAnswers.some(v => v !== '')) {
        /* 匹配键盘类型 */
            let { calcType, symbols, prevBoardType, fullFirst } = _computeType({
                rightAnswers,
                boardType,
            });
            this.matchBoardType = calcType;
            this.symbols = symbols;
            this.prevBoardType = prevBoardType;
            this.fullFirst = fullFirst;
        }
    },
    methods: {
        // 点击添加光标
        addcursor: function (event, i, j, k, dir) {
            if (this.writable) {
                let { boardType, symbols, matchBoardType, prevBoardType, matchBoardModel: boardModel, boardChoice, fullFirst } = this;
                if (this.testdata.msubmitflag === 0) { // qti调用键盘
                    /* 不指定boardType时，键盘类型为根据答案匹配 */
                    this.$addcursor(this, boardType === 'none' ? matchBoardType : boardType, event, i, j, k, dir, {
                        symbols, prevBoardType, boardModel, boardChoice, fullFirst,
                    });
                }
            }
        },
        // 光标是否在公式里
        is_cursor: function (value) {
            let flag = value.up.findIndex((value, index, arr) => {
                return value.name === 'cursor';
            });
            if (flag === -1) {
                flag = value.down.findIndex((value, index, arr) => {
                    return value.name === 'cursor';
                });
            }
            return flag !== -1 ? 1 : 0;
        },
        /* 格式化输入的值 */
        formatVal (arr) {
            let res = '';
            arr.forEach(({ value = '', name = 'aime' }) => {
                switch (name) {
                    case 'aime':
                        res += value;

                        break;
                    case 'fraction':
                        res += `\\frac {${this.formatVal(value.up)}} {${this.formatVal(value.down)}}`;

                        break;
                    case 'sqrt2':
                        res += `\\sqrt {${this.formatVal(value.down)}}`;

                        break;
                    case 'sqrt3':
                        res += `\\sqrt[{3}] {${this.formatVal(value.down)}}`;

                        break;
                    case 'aimsup':
                        res += `{${this.formatVal(value.up)}}^{${this.formatVal(value.down)}}`;

                        break;
                    case 'aimsub':
                        res += `{${this.formatVal(value.up)}}_{${this.formatVal(value.down)}}`;

                        break;
                }
            });
            return res;
        },

        formulaClick (info, key, key1) {
            this.addcursor(info.event, key, key1, info.idx, info.site);
        },
    },
};

</script>

<style lang='scss'>
  @import "iminputdiv";

  .spell {
    font-family: 'customFont';
  }

  .im-wrap {
    min-width: 100px;
    min-height: 50px;
    border-bottom: 1px solid #13d098;
    background: #d2efe6;
  }

  .im-select {
    background: #13d098;
  }

  .im-content {
    word-break: break-all;
  }

  .im-ipt-img {
    display: inline-block;
    overflow: hidden;
    border: 1px solid #13d098;
    border-radius: 8px;
  }
</style>
